function [caldt_sorted , X_sorted] = sort_High_Low(caldt,X,portfolios)

% This function sorts the input variable 'X' into percentile buckets as defined by the
% varable 'portfolios'

X_temp = X(:,1);

% first do the sort
prctiles_t = prctile(X_temp,portfolios);                            % Vector of percentile buckets

for p = 1:length(portfolios)-1
    indx = and(X_temp >= prctiles_t(p) , X_temp < prctiles_t(p+1));      % locate and drop into buckets
    X_sorted{p,1} = X(indx,:);
    caldt_sorted{p,1} = caldt(indx,1);
end

end